package com.base.web.socket.utils;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.base.common.redis.RedisUtils;
import com.base.common.utils.DateUtils;
import com.base.web.socket.entity.ChatMessage;

@Component
public class ChatMsgUtils {

	private static ChatMsgUtils chatMsgUtils;

	private ChatMsgUtils(){
		chatMsgUtils = this;
	}
	
	private final static long MSG_SURVIVE_TIME = 3 * 24 * 60 * 60; //单位：秒
	
	private final static String MSG_KEY = "base:socket:";
	
	@Resource
	private RedisUtils redis;
	
	public static synchronized void saveMsg(ChatMessage msg, String userId, String myName) {
		if(StringUtils.isBlank(userId) || StringUtils.isBlank(msg.getFriendId())) {
			return;
		}
		if(StringUtils.isBlank(msg.getContent())) {
			return;
		}
		msg.setCreaterTime(DateUtils.getDateTime());
		
		//缓存发送的消息
		msg.setType(1);
		chatMsgUtils.redis.setList(getKey(userId, msg.getFriendId()), msg, MSG_SURVIVE_TIME);
		
		String key = getKey(msg.getFriendId(), userId);
		//缓存接收的消息
		msg.setType(0);
		msg.setFriendId(userId);
		msg.setFriendName(myName);
		chatMsgUtils.redis.setList(key, msg, MSG_SURVIVE_TIME);
	}
	
	
	public static String getKey(String k1, String k2) {
		return MSG_KEY + k1 + ":" + k2;
	}
}
